import {defineStore} from "pinia";
import {computed, ref} from "vue";
import {
    ProductUnitCreate,
    ProductUnitDelete,
    ProductUnitList,
    ProductUnitUpdate
} from "@/services/api/product/units.ts";
import {useOrgStore} from "@/store/modules/organization";
import useMessage from "@/utils/useMessage.ts";

export const useProductUnitStore = defineStore('productUnits',()=>{
    const dataSource = ref<ProductUnitType[]>([])
    const loading = ref<boolean>(false)
    const searchTerm = ref<string>('')
    const orgStore = useOrgStore()

    const data = computed(()=>{
        const term = searchTerm.value.trim().toLowerCase()
        if (!term) return dataSource.value
        return dataSource.value.filter(item=>item.name.toLowerCase().includes(term))
    })
    const fetchList = async (force?:boolean)=>{
        if(!force && dataSource.value.length > 0){
             return
        }
        try {
            loading.value = true
            const res = await ProductUnitList(orgStore.id)
            if (res.code === 200){
                dataSource.value = res.data
            }
        }catch{
        }finally {
            setTimeout(()=>loading.value = false,100)
        }
    }
    const create = async (form:ProductUnitFormType)=>{
        const res = await ProductUnitCreate(form)
        if (res.code === 200){
            await fetchList(true)
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    const update = async (form:ProductUnitFormType)=>{
        if (!form.id){
            useMessage(500,'请选择要修改的单位')
            return false
        }
        const res = await ProductUnitUpdate(form.id,form)
        if (res.code === 200){
            const item = dataSource.value.find(item=>item.id === form.id)
            if (item){
                Object.assign(item,form)
            }
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    const remove = async (id:number)=>{
        const res = await ProductUnitDelete(id)
        if (res.code === 200){
            dataSource.value = dataSource.value.filter(item=>item.id !== id)
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    return {
        dataSource,
        fetchList,
        create,
        update,
        remove,
        data,
        searchTerm,
        loading
    }
})